package sword.T59;

import java.util.Deque;
import java.util.LinkedList;

/**
 * @Author: 18362
 * @Create: 2022-04-10 13:59:25 星期日
 */
class Solution {
    public int[] maxSlidingWindow(int[] nums, int k) {
        if (nums.length == 0)
            return new int[]{};
        int[] res = new int[nums.length-k+1];
        Deque<Integer> queue = new LinkedList<>();
        for (int i=0; i<k-1 && i<nums.length; ++i) {
            while (!queue.isEmpty() && nums[queue.getLast()] <= nums[i])
                queue.removeLast();
            queue.addLast(i);
        }
        for (int i=k-1; i<nums.length; ++i) {
            while (!queue.isEmpty() && nums[queue.getLast()] <= nums[i])
                queue.removeLast();
            queue.addLast(i);
            res[i-k+1] = nums[queue.getFirst()];
            if (queue.getFirst() == i-k+1)
                queue.removeFirst();
        }
        return res;
    }
}